'''
https://leetcode.cn/problems/lMSNwu/
'''

from utils import *


class Solution:
    def reverseList(self, head):
        prev, cur = None, head
        while cur:
            next = cur.next
            cur.next = prev
            prev = cur
            cur = next
        return prev

    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        l1 = self.reverseList(l1)
        l2 = self.reverseList(l2)
        res = ListNode(-1)
        cur = res
        carry = 0
        while carry or l1 or l2:
            val = 0
            if l1:
                val += l1.val
                l1 = l1.next
            if l2:
                val += l2.val
                l2 = l2.next
            val += carry
            carry = 1 if val >= 10 else 0
            val = val % 10
            cur.next = ListNode(val)
            cur = cur.next
        return self.reverseList(res.next)


arr1 = [7, 2, 4, 3]
arr2 = [5, 6, 4]
l1 = generate_list(arr1)
l2 = generate_list(arr2)
print_list(Solution().addTwoNumbers(l1, l2))
